<?php

namespace App\Http\Controllers\Api;

use App\Constant;
use App\Enums\AuditStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentStatus;
use App\Enums\ProductStatus;
use App\Events\OrderPaid;
use App\Http\Controllers\Controller;
use App\Models\Enterprise;
use App\Models\OrderPayment;
use App\Models\UserAuth;
use App\Models\YeepayWallet;
use App\Services\YeepayService;
use Illuminate\Support\Arr;

class YeepayController extends Controller
{
    /** @var YeepayService */
    private $yeepayService;

    /**
     * YeepayController constructor.
     */
    public function __construct(YeepayService $yeepayService)
    {
        $this->yeepayService = $yeepayService;
    }

    /** 支付回调 */
    public function payNotify()
    {
        $rawData = urldecode(request()->response);
        $data = $this->yeepayService->decryptData($rawData);
        \Log::channel(Constant::LOG_CHANNEL_YEEPAY)->info('PAY_NOTIFY', $data);
        $outOrderNo = Arr::get($data, 'orderId');
        $payment = OrderPayment::query()->where('out_order_no', $outOrderNo)->first();
        if ($payment->pay_status->is(PaymentStatus::PAYING)) {
            \DB::transaction(function () use ($payment) {
                $orderInfo = $this->yeepayService->queryOrder($payment->out_order_no);
                $merchantFee = toFen(Arr::get($orderInfo, 'merchantFee', 0));
                $payment->pay_status = PaymentStatus::FINISHED;
                $payment->pay_time = Arr::get($orderInfo, 'paySuccessDate', now());
                $payment->receive_amount = $payment->pay_amount - $merchantFee;
                $payment->save();

                $order = $payment->order;
                if ($order->order_status->is(OrderStatus::NOT_PAY())) {
                    $order->order_status = OrderStatus::PAID;
                    $order->save();

                    //转售订单标记为停止发行
                    $product = $order->product;
                    if ($order->is_resale) {
                        $product->status = ProductStatus::STOP;
                        $product->save();
                    }

                    OrderPaid::dispatch($order);
                }
            });
        }

        return 'SUCCESS';
    }

    /** 小微商户注册回调 */
    public function microRegisterNotify()
    {
        $rawData = urldecode(request()->response);
        $data = $this->yeepayService->decryptData($rawData);
        \Log::channel(Constant::LOG_CHANNEL_YEEPAY)->info('MICRO_REGISTER_NOTIFY', $data);
        $requestNo = Arr::get($data, 'requestNo');
        $status = Arr::get($data, 'applicationStatus');
        $auditOpinion = Arr::get($data, 'auditOpinion');

        $auth = UserAuth::query()->where('yeepay_request_no', $requestNo)->first();
        if (!$auth) {
            return 'SUCCESS';
        }
        if ('REVIEW_BACK' === $status) {
            $auth->audit_status = AuditStatus::REJECT();
            $auth->reject_reason = $auditOpinion;
            $auth->save();
        }
        if ('COMPLETED' === $status) {
            $auth->audit_status = AuditStatus::PASS();
            $auth->reject_reason = '';
            $auth->merchant_no = Arr::get($data, 'merchantNo');
            $auth->save();
        }

        return 'SUCCESS';
    }

    public function enterpriseRegisterNotify()
    {
        $rawData = urldecode(request()->response);
        $data = $this->yeepayService->decryptData($rawData);
        \Log::channel(Constant::LOG_CHANNEL_YEEPAY)->info('ENTERPRISE_REGISTER_NOTIFY', $data);
        $requestNo = Arr::get($data, 'requestNo');
        $status = Arr::get($data, 'applicationStatus');
        $auditOpinion = Arr::get($data, 'auditOpinion');

        $enterprise = Enterprise::query()->where('requestNo', $requestNo)->first();
        if (!$enterprise) {
            return 'SUCCESS';
        }
        if ('REVIEW_BACK' === $status) {
            $enterprise->applicationStatus = $status;
            $enterprise->reject_reason = $auditOpinion;
            $enterprise->save();
        }
        if ('COMPLETED' === $status) {
            $enterprise->applicationStatus = $status;
            $enterprise->reject_reason = $auditOpinion;
            $enterprise->save();
        }

        return 'SUCCESS';
    }

    /** 钱包开通回调 */
    public function openWalletNotify()
    {
        $rawData = urldecode(request()->response);
        $data = $this->yeepayService->decryptData($rawData);
        \Log::channel(Constant::LOG_CHANNEL_YEEPAY)->info('OPEN_WALLET_NOTIFY', $data);

        $wallet = YeepayWallet::query()->where('merchant_user_no', Arr::get($data, 'merchantUserNo'))->first();
        if ($wallet) {
            $wallet->wallet_user_no = Arr::get($data, 'walletUserNo');
            $wallet->merchant_no = Arr::get($data, 'merchantNo');
            $wallet->save();
        }

        return 'SUCCESS';
    }
}
